package com.software.loginregister.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.software.loginregister.R;
import com.software.loginregister.entity.TasteItem;

import java.util.ArrayList;
import java.util.List;

public class TasteAdapter extends RecyclerView.Adapter<TasteAdapter.TasteViewHolder> {
    private List<TasteItem> tasteItems;

    public TasteAdapter(List<TasteItem> tasteItems) {
        this.tasteItems = tasteItems;
    }

    @NonNull
    @Override
    public TasteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_taste_selection, parent, false);
        return new TasteViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull TasteViewHolder holder, int position) {
        TasteItem item = tasteItems.get(position);
        holder.ivTaste.setImageResource(item.getImageRes());
        holder.tvTasteName.setText(item.getName());

        // 设置选中状态
        holder.ivSelected.setVisibility(item.isSelected() ? View.VISIBLE : View.GONE);

        holder.itemView.setOnClickListener(v -> {
            item.setSelected(!item.isSelected());
            holder.ivSelected.setVisibility(item.isSelected() ? View.VISIBLE : View.GONE);
        });
    }

    @Override
    public int getItemCount() {
        return tasteItems.size();
    }

    static class TasteViewHolder extends RecyclerView.ViewHolder {
        ImageView ivTaste;
        ImageView ivSelected;
        TextView tvTasteName;

        TasteViewHolder(@NonNull View itemView) {
            super(itemView);
            ivTaste = itemView.findViewById(R.id.iv_taste);
            ivSelected = itemView.findViewById(R.id.iv_selected);
            tvTasteName = itemView.findViewById(R.id.tv_taste_name);
        }
    }
    // 添加获取选中的口味项的方法
    public List<TasteItem> getSelectedItems() {
        List<TasteItem> selectedItems = new ArrayList<>();
        for (TasteItem item : tasteItems) {
            if (item.isSelected()) {
                selectedItems.add(item);
            }
        }
        return selectedItems;
    }
}